﻿using BCCommon;
using BCEntity.OA.AuxiliaryRule;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace BCData.OA.AuxiliaryRule
{
    /// <summary>
    /// OA系统辅助规则
    /// </summary>
	public class AuxiliaryRuleData : IAuxiliaryRuleData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM OA_AuxiliaryRule";
        private const string QUERY = @"SELECT AuxiliaryRuleId,CreateTime,AuxiliaryRuleName,RelatedType,PageBusinessMappingDepartmentId,RelatedWorkflowCategoryId,MethodName,ServiceName,
                                            ServiceMethodName,ServiceMethodParameters 
                                        FROM OA_AuxiliaryRule";
        public AuxiliaryRuleData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public async Task<bool> Exists(long auxiliaryRuleId)
        {
            string sql = string.Format(@"{0} WHERE AuxiliaryRuleId=?AuxiliaryRuleId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AuxiliaryRuleId", auxiliaryRuleId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> Exists(string auxiliaryRuleName)
        {
            string sql = string.Format(@"{0} WHERE AuxiliaryRuleName=?AuxiliaryRuleName", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AuxiliaryRuleName", auxiliaryRuleName, DbType.AnsiString);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> ExistsByPageBusinessConfigId(long pageBusinessMappingDepartmentId)
        {
            string sql = string.Format(@"{0} WHERE PageBusinessMappingDepartmentId=?PageBusinessMappingDepartmentId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?PageBusinessMappingDepartmentId", pageBusinessMappingDepartmentId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<AuxiliaryRuleEntity> Add(AuxiliaryRuleEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("OA_AuxiliaryRule", new string[] { "AuxiliaryRuleName", "RelatedType", "MethodName", "ServiceName", "ServiceMethodName",
                "PageBusinessMappingDepartmentId","RelatedWorkflowCategoryId" });
            sql = string.Format("{0} {1} WHERE AuxiliaryRuleId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AuxiliaryRuleName", entity.AuxiliaryRuleName, DbType.AnsiString, size: 20);
            parameters.Add("?RelatedType", entity.RelatedType.ToString(), DbType.AnsiString);
            parameters.Add("?MethodName", entity.MethodName, DbType.AnsiString, size: 50);
            parameters.Add("?ServiceName", entity.ServiceName, DbType.AnsiString, size: 200);
            parameters.Add("?ServiceMethodName", entity.ServiceMethodName, DbType.AnsiString, size: 100);
            parameters.Add("?PageBusinessMappingDepartmentId", entity.PageBusinessMappingDepartmentId, DbType.Int64, size: 20);
            parameters.Add("?RelatedWorkflowCategoryId", entity.RelatedWorkflowCategoryId, DbType.Int64, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<AuxiliaryRuleEntity>(sql, parameters, databaseContext.Transaction);

        }

        public async Task<AuxiliaryRuleEntity> Update(AuxiliaryRuleEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("OA_AuxiliaryRule", new string[] { "AuxiliaryRuleName", "RelatedType", "PageBusinessMappingDepartmentId", "RelatedWorkflowCategoryId",
                "MethodName", "ServiceName", "ServiceMethodNameServiceMethodParameters" }, new string[] { "AuxiliaryRuleId" });
            sql = string.Format("{0} {1} WHERE AuxiliaryRuleId=?AuxiliaryRuleId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AuxiliaryRuleId", entity.AuxiliaryRuleId, DbType.Int64, size: 20);
            parameters.Add("?AuxiliaryRuleName", entity.AuxiliaryRuleName, DbType.AnsiString, size: 20);
            parameters.Add("?RelatedType", entity.RelatedType.ToString(), DbType.AnsiString);
            parameters.Add("?PageBusinessMappingDepartmentId", entity.PageBusinessMappingDepartmentId, DbType.Int64, size: 20);
            parameters.Add("?RelatedWorkflowCategoryId", entity.RelatedWorkflowCategoryId, DbType.Int64, size: 20);
            parameters.Add("?MethodName", entity.MethodName, DbType.AnsiString, size: 50);
            parameters.Add("?ServiceName", entity.ServiceName, DbType.AnsiString, size: 200);
            parameters.Add("?ServiceMethodName", entity.ServiceMethodName, DbType.AnsiString, size: 100);
            parameters.Add("?ServiceMethodParameters", entity.ServiceMethodParameters, DbType.AnsiString, size: 1000);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<AuxiliaryRuleEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<bool> Delete(long auxiliaryRuleId)
        {
            string sql = @"DELETE FROM OA_AuxiliaryRule WHERE AuxiliaryRuleId=?AuxiliaryRuleId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AuxiliaryRuleId", auxiliaryRuleId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }

        public async Task<AuxiliaryRuleEntity> GetEntity(long auxiliaryRuleId)
        {
            string sql = string.Format(@"{0} WHERE AuxiliaryRuleId=?AuxiliaryRuleId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AuxiliaryRuleId", auxiliaryRuleId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<AuxiliaryRuleEntity>(sql, parameters);
        }
        public async Task<AuxiliaryRuleEntity> GetEntityByPageBusinessConfigId(long pageBusinessMappingDepartmentId)
        {
            string sql = string.Format(@"{0} WHERE PageBusinessMappingDepartmentId=?PageBusinessMappingDepartmentId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?PageBusinessMappingDepartmentId", pageBusinessMappingDepartmentId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<AuxiliaryRuleEntity>(sql, parameters);
        }

        public async Task<IEnumerable<AuxiliaryRuleEntity>> GetList()
        {
            return await this.databaseContext.Slave.QueryAsync<AuxiliaryRuleEntity>(QUERY);
        }

        public async Task<(IEnumerable<AuxiliaryRuleEntity>, int)> Query(string auxiliaryRuleName, DateTime? start, DateTime? end, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(auxiliaryRuleName))
            {
                wheres.Add("AuxiliaryRuleName LIKE CONCAT('%',CONCAT(?AuxiliaryRuleName,'%'))");
                parameters.Add("?AuxiliaryRuleName", auxiliaryRuleName, DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime DESC LIMIT {2},{3}; SELECT COUNT(1) FROM OA_AuxiliaryRule {1}",
                   QUERY,
                   wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                   (pageIndex - 1) * pageSize,
                   pageSize);
            return await this.databaseContext.Slave.QueryMultipleAsync<AuxiliaryRuleEntity,int>(sql, parameters);
        }
    }
}
